<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--contain-->
    <el-card>
      <!--添加角色-->
      <el-button type="primary" @click="addRolesVisible=true">添加角色</el-button>
      <!--table-->
      <el-table :data="rolesList" stripe style="width: 100%">
        <el-table-column type="expand">
          <template v-slot:default="scope">
            <el-row
              v-for="(item1,in1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom','flexcenter',in1===0?'bdtop':'']"
            >
              <!--一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removTagrights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!--二级权限-->
                <el-row v-for="(item2) in item1.children" :key="item2.id" class="flexcenter">
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removTagrights(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!--三级权限-->
                    <el-tag
                      closable
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      @close="removTagrights(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot:default="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="editTreeRights(scope.row)"
            >设置权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--添加角色对话框-->
    <el-dialog title="添加角色" :visible.sync="addRolesVisible" width="50%" @closed="resetAddRoles">
      <el-form ref="addRolesRef" :model="queryAddRoles" label-width="80px" :rules="rolesRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryAddRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="queryAddRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑角色对话框-->
    <el-dialog title="添加角色" :visible.sync="editRolesVisible" width="50%" @closed="resetEditRoles">
      <el-form ref="editRolesRef" :model="editRolesForm" label-width="80px" :rules="rolesRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitEditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--树形分配权限-->
    <el-dialog
      title="分配权限"
      :visible.sync="treeRightsVisible"
      width="50%"
      @closed="defaultTreeKeys = []"
    >
      <el-tree
        :data="treeRightsData"
        show-checkbox
        node-key="id"
        ref="treeRightsRef"
        :default-expanded-keys="defaultTreeKeys"
        :default-checked-keys="defaultTreeKeys"
        :props="treetProps"
      ></el-tree>
      <span slot="footer">
        <el-button @click="treeRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitTreeRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      queryAddRoles: {
        roleName: '',
        roleDesc: ''
      },
      // dialog对话框
      addRolesVisible: false,
      editRolesVisible: false,
      treeRightsVisible: false,
      // 角色添加验证
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度为3到8个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 5, max: 20, message: '长度为5到20个字符', trigger: 'blur' }
        ]
      },
      editRolesForm: {},
      treeRightsData: [],
      treetProps: {
        children: 'children',
        label: 'authName'
      },
      defaultTreeKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色列表获取失败！')
      }
      this.rolesList = res.data
    },
    // 添加角色
    addRoles() {
      // 表单预验证
      this.$refs.addRolesRef.validate(async (valid, obj) => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.queryAddRoles)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.getRolesList()
        this.addRolesVisible = false
      })
    },
    // 重置添加表单对话框
    resetAddRoles() {
      this.$refs.addRolesRef.resetFields()
    },
    // 编辑获取角色信息
    async editRoles(id) {
      this.editRolesVisible = true
      const { data: res } = await this.$http.get(`roles/${id}`)
      this.editRolesForm = res.data
    },
    // 重置编辑表单对话框
    resetEditRoles() {
      this.$refs.editRolesRef.resetFields()
    },
    // 提交修改角色信息
    commitEditRoles() {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesForm.roleId}`,
          this.editRolesForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('角色编辑失败！')
        }
        this.getRolesList()
        this.editRolesVisible = false
      })
    },
    // 删除角色
    deleteRoles(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('角色删除失败！')
          }
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除tag权限标签
    async removTagrights(roles, rightsid) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${roles.id}/rights/${rightsid}`
          )

          if (res.meta.status !== 200) {
            return this.$message.error('取消权限失败！')
          }
          roles.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限
    async editTreeRights(roles) {
      this.roleId = roles.id
      this.treeRightsVisible = true
      // 获取树形权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.treeRightsData = res.data
      // 递归调用获取三级权限id
      this.getTreeKeys(roles, this.defaultTreeKeys)
    },
    // 获取所有三级权限的id(递归调用)
    getTreeKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getTreeKeys(item, arr)
      })
    },
    async commitTreeRights() {
      const rids = [
        this.$refs.treeRightsRef.getCheckedKeys(),
        ...this.$refs.treeRightsRef.getHalfCheckedKeys()
      ].join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: rids }
      )
      if (res.meta.status !== 200) return this.$message.error('更新失败！')
      this.$message.success('更新成功！')
      this.treeRightsVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.bdbottom {
  border-bottom: 2px solid #eee;
}
.bdtop {
  border-top: 2px solid #eee;
}
.el-tag {
  margin: 7px;
}
.flexcenter {
  display: flex;
  align-items: center;
}
.el-icon-caret-right {
  margin-left: 15px;
}
</style>
